package service

import (
	"mime/multipart"
	"shopping/dao/mysql"
	"shopping/errno"
	"shopping/model"
	"shopping/utils/csv_helper"
	"shopping/utils/pagination"
)

// CategoryService 商品分类Service
type CategoryService struct {
	categoryDao *mysql.CategoryDao
}

// NewCategoryService 实例化商品分类service
func NewCategoryService(dao *mysql.CategoryDao) *CategoryService {
	return &CategoryService{
		categoryDao: dao,
	}
}

// Create 创建分类
func (service *CategoryService) Create(category *model.Category) error {
	// 判断商品分类是否存在
	existCity := service.categoryDao.GetByName(category.Name)
	if len(existCity) > 0 {
		return errno.ErrCategoryExistWithName
	}
	// 插入商品分类数据
	err := service.categoryDao.Create(category)
	if err != nil {
		return err
	}
	return nil
}

// BulkCreate 批零创建分类
func (service *CategoryService) BulkCreate(fileHeader *multipart.FileHeader) (int, error) {
	categories := make([]*model.Category, 0)
	bulkCategory, err := csv_helper.ReadCsv(fileHeader)
	if err != nil {
		return 0, err
	}
	for _, categoryVariables := range bulkCategory {
		categories = append(categories, model.NewCategory(categoryVariables[0], categoryVariables[1]))
	}
	count, err := service.categoryDao.BulkCreate(categories)
	if err != nil {
		return count, err
	}
	return count, nil
}

// GetALl 获得分页商品分类
func (service *CategoryService) GetALl(page *pagination.Pages) *pagination.Pages {
	categories, count, err := service.categoryDao.GetAll(page.Page, page.PageSize)
	if err != nil {

	}
	page.Items = categories
	page.TotalCount = count
	return page
}
